﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using OOXMLValidation.Api;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Validation;

namespace OOXMLValidation.Cmd
{
    class Program
    {
        static int Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("OOXMLValidation 1.0 - By Robert te Kaat");
                Console.WriteLine();
                Console.WriteLine("Usage: OOXMLValidation.Cmd <package>");
                Console.WriteLine("   eg: OOXMLValidation.Cmd order.docx");
                return 1;
            }

            try
            {
                using (Stream packageStream = File.Open(args[0], FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    List<ValidationErrorInfo> errors;
                    OpenXmlPackage package = null;
                    if (args[0].ToLowerInvariant().EndsWith(".pptx"))
                    {
                        package = (OpenXmlPackage)PresentationDocument.Open(packageStream, false);
                    }
                    else if (args[0].ToLowerInvariant().EndsWith(".xlsx"))
                    {
                        package = (OpenXmlPackage)SpreadsheetDocument.Open(packageStream, false);
                    }
                    else
                    {
                        package = (OpenXmlPackage)WordprocessingDocument.Open(packageStream, false);
                    }

                    if (PackageValidator.Validate(package, out errors))
                    {
                        Console.WriteLine("{0} validation error(s) found:\n", errors.Count);
                        foreach (ValidationErrorInfo valError in errors)
                        {
                            Console.WriteLine("{1} ({0}) - {2}\n{3}\n",
                                valError.ErrorType,
                                (valError.Part != null ? valError.Part.Uri : null),
                                (valError.Path != null ? valError.Path.XPath : null),
                                valError.Description);
                        }
#if DEBUG
                        Console.Write("Press a key to exit...");
                        Console.ReadKey();
#endif
                        return 3;
                    }

                    return 0;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error while processing the package: " + ex.Message);
                return 2;
            }
        }
    }
}
